let changeImgDom = $('.changeImg'),
    title = $('.imgContainer h3'),
    imgBlockDom = $('.imgBlock'),
    imgGapDom = $('.imgGap'),
    spanDom = $('.slider span'),
    sliderDom = $('.slider'),
    imgBoxDom = $('.imgBox'),
    imgList = ['t1.png', 't2.png', 't3.png', 't4.png', 't5.png'],
    btnDom = $('.slider button');

function $(selector) {
    return document.querySelector(selector)
}

function bindEvent() {
    btnDom.onmousedown = function (e) {
        // 取消动画
        btnDom.style.transition = 'none'
        imgBlockDom.style.transition = 'none'

        imgBlockDom.style.opacity = 1
        title.innerHTML = '拖动图片完成验证'
        title.style.color = 'black'
        spanDom.style.opacity = 0
        sliderDom.onmousemove = function (ev) {
            var left = ev.clientX - sliderDom.offsetLeft - e.offsetX
            if (left < -2) {
                left = -2
            }
            if (left > sliderDom.offsetWidth - imgBlockDom.offsetWidth) {
                left = sliderDom.offsetWidth - imgBlockDom.offsetWidth
            }
            btnDom.style.left = left + 'px'
            imgBlockDom.style.left = left + 'px'
        }
    }
    document.onmouseup = function () {
        var dis = imgBlockDom.offsetLeft - imgGapDom.offsetLeft
        if (-5 < dis && dis < 5) {
            imgBlockDom.style.opacity = 0
            imgGapDom.style.opacity = 0
            title.innerHTML = '验证成功'
            title.style.color = 'red'

            document.onmouseup = btnDom.onmousedown = sliderDom.onmousemove = false
        } else {
            btnDom.style.transition = 'all 0.5s'
            imgBlockDom.style.transition = 'all 0.5s'
            btnDom.style.left = '-2px'
            imgBlockDom.style.left = '0px'
            sliderDom.onmousemove = false
            title.innerHTML = '验证失败'
            title.style.color = 'green'
            spanDom.style.opacity = 1
        }
    }

    changeImgDom.onclick = init
}

function main() {
    init()
    bindEvent()
}

function init() {
    var imgIndex = Math.floor(Math.random() * imgList.length + 1)
    imgBoxDom.style.backgroundImage = `url(./img/t${imgIndex}.png)`
    imgBlockDom.style.backgroundImage = `url(./img/t${imgIndex}.png)`


    var changeTop = imgBoxDom.offsetHeight - imgBlockDom.offsetHeight
    var changeLeft = imgBoxDom.offsetWidth / 2 - imgBlockDom.offsetWidth
    var left = Math.random() * changeLeft + imgBoxDom.offsetWidth / 2
    var top = Math.random() * changeTop
    imgGapDom.style.left = left + 'px'
    imgGapDom.style.top = top + 'px'
    imgBlockDom.style.top = top + 'px'
    imgBlockDom.style.backgroundPositionX = -left + 'px'
    imgBlockDom.style.backgroundPositionY = -top + 'px'
}

main()